import requests
from bs4 import BeautifulSoup
import os

def lyric_downloader(song_id):
    '''
    下载歌词关键部分
    :param song_id: 网易云歌曲id
    :return: lyric，是str
    '''
    lyric_url = 'https://music.163.com/api/song/media'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}

    #标题获取
    param = {'id':song_id}
    response1 = requests.get(url=lyric_url, params=param, headers=headers)
    lyric_page= response1.content.decode()

    soup = BeautifulSoup(lyric_page, 'lxml')

    lyric_str = soup.find('body').text
    print(lyric_str)
    try:
        lyric_dict = eval(lyric_str)
        lyric = lyric_dict['lyric']
    except:
        lyric = '纯音乐'
        print("纯音乐")

    #print(lyric)
    return lyric

def save_lyric(lyric, song_info):
    '''

    :param lyric:歌词
    :param song_info:歌曲信息
    :return:无
    '''
    if not os.path.exists(f'./{song_info}'):
        os.mkdir(f'./{song_info}')
    with open(f'./{song_info}/{song_info}.lrc', 'w', encoding='utf8') as fp:
        fp.write(lyric)

    print(song_info + '.lrc 保存完成！')


def run_lyric(song_id, song_info):
    '''
    总运行
    :param song_id:歌词
    :param song_info:歌曲信息
    :return:无
    '''
    print('获取歌词中！——————————————————')
    lyric1 = lyric_downloader(song_id)
    save_lyric(lyric1, song_info)
    print('歌词部分完成——————————————————')

if __name__ == '__main__':
    song_id = input('网易云歌曲id：') #  1824597603
    song_info = input('歌曲信息') #Porter Robinson - Musician
    run_lyric(song_id, song_info)



